package com.itheima.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


@Service(version = "1.0.0",interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {


    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Override
    public Result save(Role role) {
        roleDao.add(role);
        return Result.success(null);
    }

    @Override
    public Result findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<Role> rolePage = roleDao.findByCondition(queryPageBean.getQueryString());
        PageResult pageResult = new PageResult();
        pageResult.setRows(rolePage.getResult());
        pageResult.setTotal(rolePage.getTotal());
        return Result.success(pageResult);
    }

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public Result add(Role role) {
        roleDao.add(role);
       addGroupAndItem(role);
        return Result.success(null);
    }
    private void addGroupAndItem(Role role) {
        Integer roleId = role.getId();
        Set<Permission> permissions = role.getPermissions();
        for (Permission permission : permissions) {
            roleDao.addRoleAndpermission(roleId,permission);
        }
    }

    @Override
    public Result findById(Integer id) {
        Role role = roleDao.findById(id);
        List<Permission> permissions = roleDao.findRoleAndPermission(id);
        final HashMap<String, Object> map = new HashMap<>();
        map.put("fromData", role);
        map.put("tableData", permissions);
        return Result.success(map);
    }

    @Override
    public Result update(Role role) {
        roleDao.update(role);
        //权限部分先删后改
        //roleDao.deleteRoleAndPermission(role.getId());
        addGroupAndItem(role);
        return Result.success(null);
    }

    @Override
    public Result delete(Integer id) {
        roleDao.delete(id);
        return Result.success(null);
    }


}
